<template>
  <div class="supplier-check setting-content">
    <h2 class="setting-header">
      <strong>
        <span>子账号管理</span>
      </strong>
      
    </h2>
    <div class="top-info"  style="margin: 10px 0">
      <!-- <SearchCmp
        v-if="searchCmpArray.length"
        :searchCmpArray="searchCmpArray"
        :searchForm="queryData"
        @onSubmit="handleSearch"
      /> -->
      <div class="left-box">
        <el-button type="primary" @click="handleAddUser">添加成员</el-button>
        <p>剩余可授权账号数量<span>({{maxCount}})</span></p>
      </div>
      <el-button type="primary" @click="getApply">审核申请</el-button>
    </div>
    <RuifoxTable
      v-loading="tableLoading"
      v-model:tableData="tableData"
      :field-list="fieldList"
      :lazy="true"
      :default-checkbox="false"
    >
      <template #default-checkbox="{ element }">
        <div class="table-div-check">
          <el-checkbox
            class="unmover"
            v-model="element.checked"
            @change="handleCheckTable(element.id)"
            size=""
          />
        </div>
      </template>

      <!-- 账号级别 -->
      <template #pid="{ element }" >
        <el-tag v-if="element.pid == 0" type="primary">主账号</el-tag>
        <el-tag v-else type="success" >子账号</el-tag>
      </template>

      <!-- 用户状态  -->
      <template #forbidState="{ element }" >
        <el-tag v-if="element.forbidState == 0" type="primary">正常</el-tag>
        <el-tag v-else type="success" >禁用</el-tag>
      </template>

      <!-- 企业状态 -->
      <template #blockState="{ element }" >
        <el-tag v-if="element.blockState == 0" type="primary">已拉黑</el-tag>
        <el-tag v-else type="success" >正常</el-tag>
      </template>

      <template #options="{ element }">
        <div class="table-td-option unmover" v-if="element.pid != 0">
          <el-button type="primary" link @click="handleEditUser(element)">
            编辑
          </el-button>
          <el-button type="primary" link @click="setMain(element)">
            设为主账号
          </el-button>
          <el-button type="primary" link @click="cancelNode(element)">
            解除绑定
          </el-button>
          <!-- <el-button type="danger" link @click="removeNode(element)">
            删除
          </el-button> -->
        </div>
      </template>
    </RuifoxTable>
    <!-- 分页器 -->
    <PaginationView
      :total="queryData.total"
      :pageSize="queryData.pageSize"
      :currentPage="queryData.currentPage"
      :allChoose="isAllChooseBtn"
      :pageChoose="isPageChooseBtn"
      :options="batchOptions"
      :checkedNum="checkedNum"
      :canChoose="false"
      @changeSize="handleSizeChange"
      @currentChange="handleCurrentChange"
      @changePageChoose="handlePageChoose"
      @changeAllChoose="handleAllChoose"
      @invertChoose="handleInvertChoose"
      @checkOption="handleBatchOptions"
      @refreshList="getAccount"
      @cancelChoose="handleResetPagination"
    />
    <!-- 添加用户 -->
    <el-dialog v-model="isShowUserDialog" :title="userFormWay === 1 ? '添加用户' : '编辑用户'" width="600px" :close-on-click-modal="false">
      <el-form ref="userFormRule" :rules="userRules" :model="userData" label-width="80px" label-position="left" :inline-message="true">
        <el-form-item label="用户名称" prop="name">
          <template #label>
          </template>
          <el-input v-model="userData.name" placeholder="请输入用户名称"></el-input>
        </el-form-item>
        <el-form-item label="登录账号" prop="account">
          <template #label>
          </template>
          <el-input v-model="userData.account" placeholder="请输入登录账号，建议使用手机号"></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-button @click="resetPassword" v-show="!isResetPass && userFormWay !== 1">重置密码</el-button>
          <el-input v-model="userData.password" readonly v-show="isResetPass || userFormWay === 1">
            <template #append v-if="userFormWay !== 1">
              <div class="done-reset-password" v-if="isResetPass">
                <i class="iconfont">&#xe655;</i>
                已重置
              </div>
            </template>
            <template #append v-else>
              <div class="reset-password" @click="initPassword" v-if="!isInitPass">生成密码</div>
              <div class="done-reset-password" v-if="isInitPass">
                <i class="iconfont">&#xe655;</i>
                已生成
              </div>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="" v-if="(isInitPass && userFormWay === 1) || (isResetPass && userFormWay !== 1)">
          <el-switch v-model="userData.send_note"></el-switch>
          <span class="switch-send-note">是否发送密码给手机号</span>
        </el-form-item>
        <!-- <el-form-item label="接口调用">
          <el-switch v-model="userData.isUseInterface"></el-switch>
        </el-form-item> -->
        <!-- <el-form-item label="描述：" prop="introduction">
          <el-input v-model="userData.introduction" type="textarea"></el-input>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="isShowUserDialog = false">取消</el-button>
          <el-button type="primary" @click="submitUserForm(userFormRule)">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 审核申请  -->
    <el-dialog v-model="applyDialog" title="申请审核" width="1000px" :before-close="handleClose">
      <RuifoxTable :loading="applyLoading" :default-checkbox="false" :default-index="true" v-model:tableData="applyData" v-model:fieldList="applyFieldList">
        <!-- 多选 -->
        <template #default-checkbox="{element}">
          <div class="table-div-check">
            <el-checkbox class="unmover" :disabled="element.state != 1" v-model="element.checked" @change="handleCheckTable(element.id)" size />
          </div>
        </template>
       
        <template #state="{element}">
          <el-tag type="primary" v-if="element.state == 1">待审核</el-tag>
          <el-tag type="success" v-if="element.state == 2">已通过</el-tag>
          <el-tag type="danger" v-if="element.state == 3">已拒绝</el-tag>
          <el-tag type="danger" v-if="element.state == 4">已过期</el-tag>
        </template>
        <template #createTime="{element}">
          <span v-if="element.createTime">{{element.createTime}}</span>
          <span v-else>--</span>
        </template>
        <template #options="{element}">
          <div class="table-td-option unmover">
            <!-- <el-button type="primary" link @click="handleCheck(element,1)">查看</el-button> -->
            <el-button type="primary" v-if="element.state == 1" link @click="handleAuditAll(2, element)">通过</el-button>
            <el-button type="primary" v-if="element.state == 1" link @click="handleAuditAll(3, element)">拒绝</el-button>
          </div>
        </template>
      </RuifoxTable>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="applyDialog = false">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted } from "vue";
import { tableList as mixTable } from "@ruifox-cms/utils";
import { 
  selectPageByEnterpriseIdUser,
  changeMainUser, 
  selectJoinApplicationEnterprise,
  updateApplicationStateEnterprise,
  insertSubAccountUser,
  unbindUser
 } from  "@/api/enterprise";
import { selectUserEntEnterprise } from  "@/api/supplier";
import { ElMessage, ElMessageBox } from "element-plus";
import {  detectionAccount, userAdd, userEdit } from '@/api/user'
import { useStore } from "vuex";
// const searchCmpArray = ref([{ label: "名称", key: "keyWords" }]);
const store = useStore();

//表格
const {
  queryData,
  tableData: oriTableData,
  tableLoading,
  checkedNum,
  isAllChooseBtn,
  isPageChooseBtn,
  // checkedList,
  // isAllSearch,
  // getTableData,
  //   handleSearch,
  handleCurrentChange,
  handleSizeChange,
  handlePageChoose,
  handleAllChoose,
  handleInvertChoose,
  handleCheckTable,
  handleResetPagination,
} = mixTable({
  getListApi: selectPageByEnterpriseIdUser,
  // batchFuncApi: deleteByIdsCourse,
});

//分页器
const defaultQuery = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10,
  enterpriseId: "",
});
Object.assign(queryData, defaultQuery);
const tableData = ref([]);

//获取数据
const getAccount = async () => {
  queryData.enterpriseId = defaultQuery.enterpriseId
  let res = await selectPageByEnterpriseIdUser(queryData);
  if (res.code == 20000) {
    oriTableData.value = res.data.list;
    tableData.value = res.data.list;
    queryData.total = res.data.total;
  }
};

//获取当前用户所属企业
const getEnterprise = async () => { 
  const res = await selectUserEntEnterprise(defaultQuery);
  defaultQuery.enterpriseId = res.data.id;
};

//解除绑定
const cancelNode = async (row) => {
  ElMessageBox.confirm("是否确认解除绑定？", "解除后无法撤回", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const res = await unbindUser({enterpriseId: row.enterpriseId, userId: row.id})
    if (res.code === 20000) {
      ElMessage.success("解除绑定成功");
      getAccount()
    }
  });
};

//设为主账号
const setMain = async (row) => { 
  const res = await changeMainUser({
    enterpriseId: row.enterpriseId,
    originId: 1,
    targetId: 2
  })
  if (res.code == 20000) {
    ElMessage.success('设置成功');
    await getEnterprise();
  }
};

//表格展示字段
const fieldList = ref([
  {
    title: "用户名",
    name: "username",
  },
  {
    title: "账号级别",
    name: "pid",
  },
  {
    title: "所属企业",
    name: "enterpriseName",
  },
  {
    title: "账号状态",
    name: "forbidState",
  },
  {
    title: "企业状态",
    name: "blockState",
  },
  {
    title: "操作",
    name: "options",
    width: 200,
  },
]);

//申请人表格展示字段
const applyFieldList = ref([
  {
    title: '用户名',
    name: 'userName',
  },
  {
    title: '说明',
    name: 'remark',
  },
  {
    title: '状态',
    name: 'state',
  },
  {
    title: '申请时间',
    name: 'createTime',
  },
  {
    title: '操作',
    width: 120,
    fixed: 'right',
    name: 'options',
  },
])

//查询当前企业的申请信息
const applyData = ref([])
const applyDialog = ref(false)
const applyloading = ref(false)
const getApply = async () => {
  applyDialog.value = true
  let theId = defaultQuery.enterpriseId
  let res = await selectJoinApplicationEnterprise({ id: theId }).finally(() => {
    applyloading.value = false
  })
  applyData.value = res.data
  console.log("applyData.value",applyData.value);
  applyloading.value = false
}

//审核申请人是否通过
const handleAuditAll = async (state, row) => {
  const res = await updateApplicationStateEnterprise({
    id: row.id,
    reviewOpinion: "",
    state: state,
  });
  if (res.code === 20000) {
    ElMessage.success("操作成功");
    getAccount()
    getApply()
  }
}

//获取系统设置最多子账号
const maxCount = ref()
const getSetting = async () => {
  maxCount.value = store.state.setting.setting.maxSubAccount - tableData.value.length
  console.log("maxCount",maxCount.value);
  if(maxCount.value <= 0){
    maxCount.value = 0
  }
}

onMounted(async() => {
  await getEnterprise();
  await getAccount();
  await getSetting()
});


// 添加用户
const defaultUserData = {
  id: null,
  roleIds: [10], //角色 10是供应商角色
  groupId: store.state.base.userInfo.groupId,
  name: '', //名称
  account: '', //用户名
  password: '', //初始密码 or 密码
  isUseInterface: true, //是否使用接口调用
  avatar: '', //头像
  introduction: '', //描述
  send_note: false //发送短信
}
const userData = reactive(Object.assign({}, defaultUserData))
// 手机号验证
const validatorPhoneNumber = async (rule, value, callback) => {
  let reg = /^1[3-9]\d{9}$/
  if (value === '') {
    callback(new Error('请输入手机号账号'))
  } else if (!reg.test(value)) {
    callback(new Error('请输入正确的手机号'))
  } else if (userFormWay.value === 1) {
    let res = await detectionAccount({ account: value })
    if (res.data.is_exist === 1) {
      callback(new Error('手机号已存在'))
    } else {
      callback()
    }
  } else {
    let res = await detectionAccount({ account: value, id: userData.id })
    if (res.data.is_exist === 1) {
      callback(new Error('手机号已存在'))
    } else {
      callback()
    }
  }
}
// 密码验证 如果是编辑则密码不需要为空验证
const validatorPassword = async (rule, value, callback) => {
  if (value === '' && userFormWay.value === 1) {
    callback(new Error('请生成密码'))
  } else {
    callback()
  }
}
// 表单
const optionLoading = ref(false) //操作状态
const userFormRule = ref()
const userRules = reactive({
  roleIds: [{ required: true, message: '请选择所属角色', trigger: 'blur' }],
  name: [{ required: true, message: '请输入用户名称', trigger: 'blur' }],
  account: [{ required: true, validator: validatorPhoneNumber, trigger: 'blur' }],
  password: [{ validator: validatorPassword, trigger: 'blur' }],
  groupId: [{ required: true, message: '请选择所属团队', trigger: 'blur' }]
})
const isShowUserDialog = ref(false)
const userFormWay = ref(1) //修改还是添加 1:添加 2:修改
const isInitPass = ref(false)
//添加用户
const handleAddUser = () => {
  //判断是否还可以增加用户
  if(maxCount.value > 0){
    if (userFormRule.value) {
      userFormRule.value.resetFields()
    }
    Object.assign(userData, defaultUserData)
    isInitPass.value = false
    userFormWay.value = 1
    isShowUserDialog.value = true
  } else {
    ElMessage.warning('用户数量已达上限，无法继续添加')
  }
}
//编辑用户
const handleEditUser = data => {
  if (userFormRule.value) {
    userFormRule.value.resetFields()
  }
  //赋值
  Object.assign(userData, defaultUserData)
  data.name = data.username
  // data.account = data.username
  Object.assign(userData, data)
  isResetPass.value = false
  userFormWay.value = 2
  userData.send_note = false
  isShowUserDialog.value = true
}
const isResetPass = ref(false)
const resetPassword = () => {
  isResetPass.value = true
  userData.send_note = true
  userData.password = generatePassword(10)
  if (userFormRule.value) {
    userFormRule.value.validateField('password')
  }
}
const initPassword = () => {
  isInitPass.value = true
  userData.send_note = true
  userData.password = generatePassword(10)
  if (userFormRule.value) {
    userFormRule.value.validateField('password')
  }
}
const generatePassword = (length) => {
  const lowercase = 'abcdefghijklmnopqrstuvwxyz'
  const uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  const numbers = '0123456789'
  const special = '!@#$%^&*'
  
  // 所有可用字符
  const allChars = lowercase + uppercase + numbers + special
  
  // 确保至少包含三种字符类型
  let password = ''
  const charTypes = [lowercase, uppercase, numbers, special]
  
  // 随机选择3种字符类型
  const selectedTypes = charTypes
    .sort(() => Math.random() - 0.5)
    .slice(0, 3)
  
  // 从每种选中的类型中至少选择一个字符
  selectedTypes.forEach(type => {
    password += type.charAt(Math.floor(Math.random() * type.length))
  })
  
  // 填充剩余长度
  while (password.length < length) {
    password += allChars.charAt(Math.floor(Math.random() * allChars.length))
  }

  return password
    .split('')
    .sort(() => Math.random() - 0.5)
    .join('')
}
const submitUserForm = async formEl => {
  if (!formEl) return
  optionLoading.value = true
  await formEl.validate(valid => {
    if (valid) {
      if (userFormWay.value === 1) {
        delete userData.id
        userAdd(userData).then(async res => {
          if (res.code === 20000 && res.data.userId) {
            //将该用户和本系统绑定
            const bindRes = await insertSubAccountUser({
              enterpriseId: defaultQuery.enterpriseId,
              userId: res.data.userId
            })
            if(bindRes.code == 20000){
              ElMessage({
                showClose: true,
                message: '添加成功',
                type: 'success'
              })
              getAccount()
            }
            optionLoading.value = false
            isShowUserDialog.value = false
          }
        })
      } else {
        if (!isResetPass.value) delete userData.password
        userEdit(userData).then(res => {
          if (res.code === 20000) {
            optionLoading.value = false
            isShowUserDialog.value = false
            ElMessage({
              showClose: true,
              message: '修改成功',
              type: 'success'
            })
            getAccount()
          }
        })
      }
    }
  })
}
</script>
<style scoped lang="scss">
.setting-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.top-info{
  display: flex;
  justify-content: space-between;
  align-items: center;
  /* margin-bottom: 20px; */
  .left-box{
    display: flex;
    align-items: center;
    p{
      font-size: 14px;
      color: $black_2;
      margin-left: 10px;
      span{
        color: $mainColor;
        font-size: 16px;
        margin-left: 5px;
      }
    }
  }
}
.switch-send-note{
  margin-left: 10px;
}
</style>
